package com.CTAtracker.android.DAO;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.CTAtracker.android.DataBase.MySQLiteHelperLine;
import com.CTAtracker.android.Models.Line;

/**
 * Class that retrieve the data of the table line from the database
 */
public class LineDataSource {

	/**
	 * The SQLite Database
	 */
	private SQLiteDatabase database;
	/**
	 * The helper to the table line in the database
	 */
	private MySQLiteHelperLine dbHelperLine;
	
	/**
	 * Create the database helper from the context 
	 * @param context the current context 
	 */
	public LineDataSource(Context context) {
		dbHelperLine = new MySQLiteHelperLine(context);
	}

	/**
	 * Open the database to be writable
	 * @throws SQLException fail to open the database
	 */
	public void open() throws SQLException {
		database = dbHelperLine.getWritableDatabase();
	}

	/**
	 * Close the database
	 */
	public void close() {
		dbHelperLine.close();
	}

	/**
	 * Get all the CTA line from the database 
	 * @return an Array List of the line
	 */
	public ArrayList<Line> getAllLine() {
		ArrayList<Line> lines = new ArrayList<Line>();

		Cursor cursor = database.query(
				MySQLiteHelperLine.TABLE_LINE,
				MySQLiteHelperLine.allColumns, 
				null, null, MySQLiteHelperLine.LINE_ID, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Line line = cursorToLine(cursor);
			lines.add(line);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return lines;
	}

	/**
	 * Create a Line from the Cursor of the database query
	 * @param cursor the cursor of the database query 
	 * @return a new line
	 */
	private Line cursorToLine(Cursor cursor) {
		Line line = new Line();
		line.set_id(cursor.getInt(0));
		line.set_nameTrack(cursor.getString(1));
		line.set_color(cursor.getString(2));
		return line;
	}
} 

